import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Space,
  Card
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { adminApi } from '../../services/api';

const { TextArea } = Input;

const CategoryManagement = () => {
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    loadCategories();
  }, []);

  const loadCategories = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const response = await adminApi.categories.list({ page, size });
      setCategories(response.data?.records || []);
      setPagination({
        current: page,
        pageSize: size,
        total: response.data?.total || 0,
      });
    } catch (error) {
      console.error('加载分类失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (pagination) => {
    loadCategories(pagination.current, pagination.pageSize);
  };

  const showModal = (category = null) => {
    setEditingCategory(category);
    setModalVisible(true);
    if (category) {
      form.setFieldsValue(category);
    } else {
      form.resetFields();
    }
  };

  const handleSubmit = async (values) => {
    try {
      if (editingCategory) {
        await adminApi.categories.update(editingCategory.id, values);
        message.success('更新分类成功');
      } else {
        await adminApi.categories.create(values);
        message.success('创建分类成功');
      }
      
      setModalVisible(false);
      loadCategories(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('保存分类失败:', error);
    }
  };

  const handleDelete = async (id) => {
    try {
      await adminApi.categories.delete(id);
      message.success('删除分类成功');
      loadCategories(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('删除分类失败:', error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            description="删除分类可能会影响相关菜品"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ 
      padding: window.innerWidth <= 768 ? '16px' : '24px',
      background: '#f8f9fa',
      minHeight: '100vh'
    }}>
      <Card 
        style={{ 
          border: 'none',
          boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
          borderRadius: '12px'
        }}
        bodyStyle={{ padding: window.innerWidth <= 768 ? '16px' : '24px' }}
      >
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center', 
          marginBottom: 20,
          flexWrap: window.innerWidth <= 768 ? 'wrap' : 'nowrap',
          gap: 12
        }}>
          <h1 style={{ 
            margin: 0, 
            fontSize: window.innerWidth <= 768 ? '20px' : '24px',
            fontWeight: 600,
            color: '#1a1a1a'
          }}>
            分类管理
          </h1>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => showModal()}
            style={{
              borderRadius: '8px',
              fontWeight: 500,
              height: window.innerWidth <= 768 ? '36px' : '40px',
              padding: window.innerWidth <= 768 ? '0 16px' : '0 20px'
            }}
          >
            新增分类
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={categories}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: window.innerWidth > 768,
            showQuickJumper: window.innerWidth > 768,
            showTotal: (total, range) => (
              <span style={{ fontSize: '13px', color: '#666' }}>
                共 {total} 条
              </span>
            ),
            size: window.innerWidth <= 768 ? 'small' : 'default',
            style: { marginTop: 16 }
          }}
          onChange={handleTableChange}
          style={{ 
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
      </Card>

      <Modal
        title={editingCategory ? '编辑分类' : '新增分类'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={window.innerWidth <= 768 ? '95%' : 600}
        style={{ 
          top: window.innerWidth <= 768 ? 20 : undefined,
          maxHeight: window.innerWidth <= 768 ? '90vh' : undefined
        }}
        bodyStyle={{ 
          padding: window.innerWidth <= 768 ? '16px' : '24px',
          maxHeight: window.innerWidth <= 768 ? 'calc(90vh - 110px)' : undefined,
          overflowY: 'auto'
        }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          size={window.innerWidth <= 768 ? 'middle' : 'large'}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[
              { required: true, message: '请输入分类名称' },
              { max: 50, message: '分类名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[
              { max: 200, message: '描述不能超过200个字符' }
            ]}
          >
            <TextArea
              placeholder="请输入分类描述（可选）"
              rows={window.innerWidth <= 768 ? 3 : 4}
              showCount
              maxLength={200}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }}>
            <div style={{ 
              display: 'flex', 
              gap: 12,
              justifyContent: 'flex-end',
              flexWrap: 'wrap'
            }}>
              <Button 
                type="primary" 
                htmlType="submit"
                style={{
                  borderRadius: '8px',
                  fontWeight: 500,
                  minWidth: window.innerWidth <= 768 ? '80px' : '100px'
                }}
              >
                {editingCategory ? '更新' : '创建'}
              </Button>
              <Button 
                onClick={() => setModalVisible(false)}
                style={{
                  borderRadius: '8px',
                  fontWeight: 500
                }}
              >
                取消
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;